package com.bluesky.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.bluesky.common.Constants;
import com.bluesky.common.bo.DictModel;
import com.bluesky.common.redis.RedisUtils;
import com.google.common.collect.Lists;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 字典缓存工具类
 *
 * @author Kevin
 */
public class DictUtils {

    public static String getCacheKey(String key) {
        return String.format(Constants.SYS_DICT_TPL, key);
    }

    public static List<DictModel> getDictList(String dictCode) {
        Object obj = SpringUtil.getBean(RedisUtils.class).get(getCacheKey(dictCode));
        return Objects.nonNull(obj) ? (List<DictModel>) obj : Lists.newArrayList();
    }

    public static String getDictLabel(String dictCode, String dictValue) {
        if (StrUtil.isBlank(dictCode) || StrUtil.isBlank(dictValue)) {
            return "";
        }
        List<DictModel> dictModelList = getDictList(dictCode);
        DictModel dictModel = dictModelList.stream().filter(x -> x.getValue().equals(dictValue)).findFirst().orElse(null);
        return Objects.nonNull(dictModel) ? dictModel.getLabel() : "";
    }

    public static String getDictValue(String dictCode, String dictLabel) {
        if (StrUtil.isBlank(dictCode) || StrUtil.isBlank(dictLabel)) {
            return "";
        }
        List<DictModel> dictModelList = getDictList(dictCode);
        DictModel dictModel = dictModelList.stream().filter(x -> x.getLabel().equals(dictLabel)).findFirst().orElse(null);
        return Objects.nonNull(dictModel) ? dictModel.getValue() : "";
    }

    public static void setDictCache(String dictCode, List<DictModel> dictModelList) {
        if (StrUtil.isBlank(dictCode) || Objects.isNull(dictModelList) || dictModelList.isEmpty()) {
            return;
        }
        SpringUtil.getBean(RedisUtils.class).set(getCacheKey(dictCode), dictModelList);
    }

    public static void clearDictCache() {
        Collection<String> keys = SpringUtil.getBean(RedisUtils.class).keys(getCacheKey("*"));
        SpringUtil.getBean(RedisUtils.class).del(keys.toArray(new String[0]));
    }

}
